﻿using Microsoft.AspNetCore.Http; 
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
using Newtonsoft.Json;
using ServiceCore.Tool.ES;
using ServiceCore.Tool.MongoDB;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ServiceCore.Tool.JD_Pay
{
    public interface IJD_API
    {
        /// <summary>
        /// 统一入住接口
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        EnterSingleMast_Result EnterSingle(JdmerchantBase Params);
        /// <summary>
        ///  应用产品
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        applySingle_Result ApplySingle(applySingle Params);
        /// <summary>
        /// 查询产品开通情况
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        queryApplySingle_Result queryApplySingle(queryApplySingle Params);
        /// <summary>
        /// 密钥查询
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        queryMerchantKeys_result queryMerchantKeys(queryMerchantKeys Params); 
        /// <summary>
        /// 下载对账单
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        JD_download_result JD_download(JD_download Params);
        /// <summary>
        /// 服务商查询商户结算状态接口
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        queryMerchantsSettle_result queryMerchantsSettle(queryMerchantsSettle Params);
        void ApplySingleQueueInQueue(string Kid);
        void ApplySingleQueueListen();
        /// <summary>
        /// 查询支付订单数据
        /// </summary>
        /// <param name="outTradeNo"></param>
        /// <param name="merchantNo"></param>
        /// <param name="desKey"></param>
        /// <param name="mdKey"></param>
        /// <returns></returns>
        querytrade_Result querytrade_for_rk(string outTradeNo, string merchantNo, string desKey, string mdKey);
        #region 支付相关
        /// <summary>
        /// 6.4.7 获取京东的openid
        /// </summary>
        /// <param name="piType"></param>
        /// <param name="merchantNo"></param>
        /// <param name="nowurl"></param>
        /// <returns></returns>
        getopenid_result get_openid(string piType, string merchantNo, string nowurl);
        /// <summary>
        /// 6.4 统一下单接口
        /// </summary>
        /// <param name="ex_params"></param>
        /// <param name="o_Item"></param>
        /// <param name="g_list"></param>
        /// <param name="dev_Item"></param>
        /// <param name="b_list"></param>
        /// <returns></returns>
        unifiedOrder_Result unifiedOrder(Ex_params ex_params, orderInfo o_Item, List<goodsInfo> g_list, deviceInfo dev_Item, List<billSplitList> b_list);
        /// <summary>
        /// 6.5 订单查询
        /// </summary>
        /// <param name="outTradeNo"></param>
        /// <param name="baseuserid"></param>
        /// <returns></returns>
        querytrade_Result querytrade(string outTradeNo, string baseuserid);
        /// <summary>
        /// 6.6 退款
        /// </summary>
        /// <param name="refund_No"></param>
        /// <param name="baseuserid"></param>
        /// <param name="amount"></param>
        /// <param name="o_Item"></param>
        /// <param name="g_list"></param>
        /// <param name="dev_Item"></param>
        /// <param name="b_list"></param>
        /// <returns></returns>
        refund_Result refund(string refund_No, string baseuserid, long amount, orderInfo o_Item, List<goodsInfo> g_list, deviceInfo dev_Item = null, List<billSplitList> b_list = null);
        /// <summary>
        ///  6.7 关闭订单 
        /// </summary>
        /// <param name="outTradeNo"></param>
        /// <param name="baseuserid"></param>
        /// <returns></returns>
        orderclose_Result orderclose(string outTradeNo, string baseuserid);
        /// <summary>
        ///  6.9 查询退款 
        /// </summary>
        /// <param name="outRefundNo"></param>
        /// <param name="baseuserid"></param>
        /// <returns></returns>
        queryrefund_Result queryrefund(string outRefundNo, string baseuserid); 
        /// <summary>
        ///  6.11 下载对账单 
        /// </summary>
        /// <param name="outRefundNo"></param>
        /// <param name="baseuserid"></param>
        /// <returns></returns>
        bill_Result bill(string billDate, string baseuserid, string billType = null);
        /// <summary>
        ///  6.12   支付结果通知
        /// </summary>
        /// <param name="InputStream"></param>
        /// <param name="baseuserid"></param>
        /// <returns></returns>
        paynotify_Result payNotify(Stream InputStream);
        /// <summary>
        ///  6.13   退款结果通知
        /// </summary>
        /// <param name="InputStream"></param>
        /// <param name="baseuserid"></param>
        /// <returns></returns>
        refundnotify_Result refundNotify(Stream InputStream);
        /// <summary>
        /// 退款查询
        /// </summary>
        /// <param name="outRefundNo"></param>
        /// <param name="merchantNo"></param>
        /// <param name="desKey"></param>
        /// <param name="mdKey"></param>
        /// <returns></returns>
        queryrefund_Result queryrefund_for_rk(string outRefundNo, string merchantNo, string desKey, string mdKey);
        #endregion
        /// <summary>
        /// 查询微信信息
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        queryMerchantWXNo_result queryMerchantWXNo(queryMerchantWXNo Params);
    }
    public class JD_API : IJD_API
    {
        private readonly IConfiguration AppSettingConfig;
        private readonly IEs_Log_Helper _log;
        private readonly IMongoDB_Client<JD_data_model> _jd_mongo;
        private readonly IHttpContextAccessor _context;
        public JD_API(IConfiguration configuration, IEs_Log_Helper Log, IMongoDB_Client<JD_data_model> Jd_mongo, IHttpContextAccessor Context)
        {
            AppSettingConfig = configuration;
            _log = Log;
            _jd_mongo = Jd_mongo;
            _context = Context;
        }

        #region 商户入驻相关 
        public string Key { get { return AppSettingConfig["JD_Pay:key"]; } }
        public string AgentNo { get { return AppSettingConfig["JD_Pay:agentNo"]; } }
        public string systemId { get { return AppSettingConfig["JD_Pay:systemId"]; } }
        public string notifyUrl { get { return AppSettingConfig["JD_Pay:notifyUrl"]; } }
        public string refund_notifyUrl { get { return AppSettingConfig["JD_Pay:refund_notifyUrl"]; } }
        /// <summary>
        ///  3.1 开始提交
        /// </summary>
        /// <returns></returns>
        public EnterSingleMast_Result EnterSingle(JdmerchantBase Params)
        {
            EnterSingleMast_Result result = new EnterSingleMast_Result();

            EnterSingleMast_Model subparams = new EnterSingleMast_Model();
            subparams.agentNo = AgentNo;
            subparams.blicUrla = Params.enterimg;
            subparams.occUrla = Params.occUrla;
            subparams.blicObaUrla = Params.blicObaUrla;
            subparams.blicTrcUrla = Params.blicTrcUrla;
            subparams.lepUrla = Params.lepUrla;
            subparams.lepUrlb = Params.lepUrlb;
            subparams.lepUrlc = Params.lepUrlc;
            subparams.img = Params.img;
            subparams.enterimg = Params.enterimg;
            subparams.innerimg = Params.innerimg;
            subparams.cardPhoto = Params.cardPhoto;
            subparams.settleManPhotoFront = Params.settleManPhotoFront;
            subparams.settleManPhotoBack = Params.settleManPhotoBack;
            subparams.settleProtocol = Params.settleProtocol;
            subparams.settleHoldingIDCard = Params.settleHoldingIDCard;
            subparams.settleHoldingBankCard = Params.settleHoldingBankCard;

            subparams.entity = new entity_base();
            subparams.entity.companyType = Params.companyType;
            subparams.entity.blicUscc = Params.blicUscc;
            subparams.entity.blicScope = Params.blicScope;
            subparams.entity.serialNo = Params.serialNo;
            subparams.entity.agentNo = AgentNo;
            subparams.entity.merchantNo = Params.merchantNo;
            subparams.entity.abMerchantName = Params.abMerchantName;
            subparams.entity.bankAccountName = Params.bankAccountName;
            subparams.entity.bankAccountNo = Params.bankAccountNo;
            subparams.entity.bankName = Params.bankName;
            subparams.entity.blicCardType = Params.blicCardType;
            subparams.entity.blicAddress = Params.blicProvince + Params.blicCity + Params.blicDistrict + Params.blicAddress;
            subparams.entity.blicCity = Params.blicCity;
            subparams.entity.blicCompanyName = Params.blicCompanyName;
            subparams.entity.blicLongTerm = Params.blicLongTerm;

            subparams.entity.blicProvince = Params.blicProvince;
            subparams.entity.blicValidityStart = Params.blicValidityStart;
            subparams.entity.blicValidityEnd = Params.blicLongTerm == "true" ? "长期" : Params.blicValidityEnd;
            subparams.entity.contactEmail = Params.contactEmail;
            subparams.entity.contactName = Params.contactName;
            subparams.entity.contactPhone = Params.contactPhone;
            subparams.entity.contactProvince = Params.contactProvince;
            subparams.entity.contactCity = Params.contactCity;
            subparams.entity.contactAddress = Params.contactProvince + Params.contactCity + Params.contactDistrict + Params.contactAddress;
            subparams.entity.ifPhyStore = Params.ifPhyStore.Value;
            subparams.entity.indTwoCode = Params.indTwoCode;
            subparams.entity.lepCardNo = Params.lepCardNo;
            subparams.entity.lepCardType = Params.lepCardType;
            subparams.entity.lepLongTerm = Params.lepLongTerm; 
            subparams.entity.lepName = Params.lepName;
            subparams.entity.lepValidityStart = Params.lepValidityStart; 

            subparams.entity.lepValidityEnd = Params.lepLongTerm == "true" ? "长期" : Params.lepValidityEnd;
            subparams.entity.priatePublic = Params.priatePublic;
            subparams.entity.regEmail = Params.regEmail;
            subparams.entity.regPhone = Params.regPhone;
            subparams.entity.settleCardPhone = Params.settleCardPhone;
            subparams.entity.storeAddress = Params.storeProvince + Params.storeCity + Params.storeDistrict + Params.storeAddress;
            subparams.entity.storeCity = Params.storeCity;
            subparams.entity.storeProvince = Params.storeProvince;
            subparams.entity.subBankCode = Params.subBankCode;
            subparams.entity.settleToCard = Params.settleToCard;
            subparams.entity.settlementPeriod = Params.settlementPeriod;
            subparams.entity.directoryList = Params.directoryList.Split(",").ToList();
            subparams.entity.blicScope = Params.blicScope;
            subparams.entity.blicUscc = Params.blicUscc;
            #region 处理entity值
            SortedDictionary<string, object> entity_dic = new SortedDictionary<string, object>();
            string companyType = Params.companyType;
            foreach (var item in subparams.entity.GetType().GetProperties())
            {
                if (item.GetValue(subparams.entity) != null)
                {
                    if (item.Name == "merchantNo")
                    {
                        if (item.GetValue(subparams.entity) == null || string.IsNullOrWhiteSpace(item.GetValue(subparams.entity).ToString()))
                        {
                            continue;
                        }
                    }
                    if (item.Name == "blicScope" || item.Name == "blicUscc")
                    {
                        if (companyType == "N")
                        {
                            continue;
                        }
                    }
                    entity_dic.AddOrPeplace(item.Name, item.GetValue(subparams.entity));
                }
            }
            //开始SIGN
            string signData = subparams.entity.serialNo + subparams.entity.lepCardNo + subparams.entity.bankAccountNo + subparams.entity.settleCardPhone;
            string sign = JD_Tool.sign(signData);
            entity_dic.AddOrPeplace("sign", sign);
            string entity_content = JsonConvert.SerializeObject(entity_dic);
            string Content = JD_Tool.Des3EncryptECB(Convert.FromBase64String(Key), entity_content);
            #endregion
            #region  处理提交值
            Dictionary<string, object> sub_params = new Dictionary<string, object>();
            foreach (var item in subparams.GetType().GetProperties())
            {
                if (item.Name == "entity")
                {
                    sub_params.AddOrPeplace(item.Name, Content);
                    continue;
                }
                if (NeedFile.Contains(item.Name))
                {
                    string url = item.GetValue(subparams) == null ? "" : item.GetValue(subparams).ToString();
                    if (!string.IsNullOrWhiteSpace(url))
                    {
                        sub_params.AddOrPeplace(item.Name, JD_Tool.FileToByte2(url));
                    }
                }
                else
                {
                    sub_params.AddOrPeplace(item.Name, item.GetValue(subparams));
                }
            }
            //处理完成以后提交请求
            try
            {
                HttpWebResponse response = JD_Tool.MultipartFormDataPost("https://psi.jd.com/merchant/enterSingle", "iPhone", sub_params);
                using (Stream myResponseStream = response.GetResponseStream())
                {
                    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                    string retString = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myResponseStream.Close();
                    if (string.IsNullOrWhiteSpace(retString))
                    {
                        result.code = "-1";
                        result.code_msg = "提交失败 对方服务器未响应";
                    }
                    else
                    {
                        result = Newtonsoft.Json.JsonConvert.DeserializeObject<EnterSingleMast_Result>(retString);
                    }
                }
            }
            catch (Exception ex)
            {
                result.code = "-1";
                result.code_msg = "提交发生异常=>" + ex.Message;
            }
            #endregion
            return result;
        }

        /// <summary>
        /// 3.2 提交产品应用
        /// </summary>
        /// <returns></returns>
        public applySingle_Result ApplySingle(applySingle Params)
        {
            applySingle_Result result = new applySingle_Result();
            SortedDictionary<string, object> entity_dic = new SortedDictionary<string, object>();
            foreach (var item in Params.GetType().GetProperties())
            {
                entity_dic.AddOrPeplace(item.Name, item.GetValue(Params));
            }
            string signData = Params.serialNo + Params.agentNo + Params.merchantNo + Params.productId + Params.payToolId;
            string sign = JD_Tool.sign(signData);
            entity_dic.AddOrPeplace("sign", sign);
            string entity_content = JsonConvert.SerializeObject(entity_dic);
            string Content = JD_Tool.Des3EncryptECB(Convert.FromBase64String(Key), entity_content);
            SortedDictionary<string, string> sub_params = new SortedDictionary<string, string>();
            sub_params.AddOrPeplace("agentNo", AgentNo);
            sub_params.AddOrPeplace("entity", Content);
            try
            {
                string data = JD_Tool.post("https://psi.jd.com/merchant/applySingle", sub_params);
                if (string.IsNullOrWhiteSpace(data))
                {
                    result.code = "-1";
                    result.message = "提交失败 对方服务器未响应";
                }
                else
                {
                    result = Newtonsoft.Json.JsonConvert.DeserializeObject<applySingle_Result>(data);
                }
            }
            catch (Exception ex)
            {
                result.code = "-1";
                result.message = "提交发生异常=>" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 3.3 查询产品开通情况
        /// </summary>
        /// <returns></returns>
        public queryApplySingle_Result queryApplySingle(queryApplySingle Params)
        {
            queryApplySingle_Result result = new queryApplySingle_Result();
            SortedDictionary<string, object> entity_dic = new SortedDictionary<string, object>();
            foreach (var item in Params.GetType().GetProperties())
            {
                entity_dic.AddOrPeplace(item.Name, item.GetValue(Params));
            }
            string signData = Params.serialNo + Params.merchantNo;
            string sign = JD_Tool.sign(signData);
            entity_dic.AddOrPeplace("sign", sign);
            string entity_content = JsonConvert.SerializeObject(entity_dic);
            string Content = JD_Tool.Des3EncryptECB(Convert.FromBase64String(Key), entity_content);
            SortedDictionary<string, string> sub_params = new SortedDictionary<string, string>();
            sub_params.AddOrPeplace("agentNo", AgentNo);
            sub_params.AddOrPeplace("entity", Content);
            try
            {
                string data = JD_Tool.post("https://psi.jd.com/merchant/status/queryApplySingle", sub_params);
                if (string.IsNullOrWhiteSpace(data))
                {
                    result.code = "-1";
                    result.message = "提交失败 对方服务器未响应";
                }
                else
                {
                    result = Newtonsoft.Json.JsonConvert.DeserializeObject<queryApplySingle_Result>(data);
                }
            }
            catch (Exception ex)
            {
                result.code = "-1";
                result.message = "提交发生异常=>" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 3.4 商户支付秘钥查询
        /// </summary>
        /// <returns></returns>
        public queryMerchantKeys_result queryMerchantKeys(queryMerchantKeys Params)
        {
            queryMerchantKeys_result result = new queryMerchantKeys_result();
            SortedDictionary<string, object> entity_dic = new SortedDictionary<string, object>();
            foreach (var item in Params.GetType().GetProperties())
            {
                entity_dic.AddOrPeplace(item.Name, item.GetValue(Params));
            }
            string signData = Params.serialNo + Params.merchantNo;
            string sign = JD_Tool.sign(signData);
            entity_dic.AddOrPeplace("sign", sign);
            string entity_content = JsonConvert.SerializeObject(entity_dic);
            string Content = JD_Tool.Des3EncryptECB(Convert.FromBase64String(Key), entity_content);
            SortedDictionary<string, string> sub_params = new SortedDictionary<string, string>();
            sub_params.AddOrPeplace("agentNo", AgentNo);
            sub_params.AddOrPeplace("entity", Content);
            try
            {
                string data = JD_Tool.post("https://psi.jd.com/merchant/status/queryMerchantKeys", sub_params);
                if (string.IsNullOrWhiteSpace(data))
                {
                    result.code = "-1";
                    result.message = "提交失败 对方服务器未响应";
                }
                else
                {
                    result = Newtonsoft.Json.JsonConvert.DeserializeObject<queryMerchantKeys_result>(data);
                }
            }
            catch (Exception ex)
            {
                result.code = "-1";
                result.message = "提交发生异常=>" + ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 3.5 对账单下载
        /// </summary>
        /// <returns></returns>
        public JD_download_result JD_download(JD_download Params)
        {
            JD_download_result result = new JD_download_result();
            SortedDictionary<string, object> entity_dic = new SortedDictionary<string, object>();
            foreach (var item in Params.GetType().GetProperties())
            {
                entity_dic.AddOrPeplace(item.Name, item.GetValue(Params));
            }
            string signData = Params.billDate + Params.agentNo;
            string sign = JD_Tool.sign(signData);
            entity_dic.AddOrPeplace("sign", sign);
            string entity_content = JsonConvert.SerializeObject(entity_dic);
            string Content = JD_Tool.Des3EncryptECB(Convert.FromBase64String(Key), entity_content);
            SortedDictionary<string, string> sub_params = new SortedDictionary<string, string>();
            sub_params.AddOrPeplace("agentNo", AgentNo);
            sub_params.AddOrPeplace("entity", Content);
            try
            {
                string data = JD_Tool.post("https://psi.jd.com/agentmerchant/download", sub_params);
                if (string.IsNullOrWhiteSpace(data))
                {
                    result.code = "-1";
                    result.message = "提交失败 对方服务器未响应";
                }
                else
                {
                    result = Newtonsoft.Json.JsonConvert.DeserializeObject<JD_download_result>(data);
                }
            }
            catch (Exception ex)
            {
                result.code = "-1";
                result.message = "提交发生异常=>" + ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 3.6 服务商查询商户结算状态接口
        /// </summary>
        /// <returns></returns>
        public queryMerchantsSettle_result queryMerchantsSettle(queryMerchantsSettle Params)
        {
            queryMerchantsSettle_result result = new queryMerchantsSettle_result();
            SortedDictionary<string, object> entity_dic = new SortedDictionary<string, object>();
            foreach (var item in Params.GetType().GetProperties())
            {
                entity_dic.AddOrPeplace(item.Name, item.GetValue(Params));
            }
            string signData = Params.agentNo + Params.merchantNo + Params.queryStartTime + Params.queryEndTime + Params.orderStatus + Params.pageNum.ToString() + Params.pageSize.ToString();
            string sign = JD_Tool.sign(signData);
            entity_dic.AddOrPeplace("sign", sign);
            string entity_content = JsonConvert.SerializeObject(entity_dic);
            string Content = JD_Tool.Des3EncryptECB(Convert.FromBase64String(Key), entity_content);
            SortedDictionary<string, string> sub_params = new SortedDictionary<string, string>();
            sub_params.AddOrPeplace("agentNo", AgentNo);
            sub_params.AddOrPeplace("entity", Content);
            try
            {
                string data = JD_Tool.post("https://psi.jd.com/merchant/status/queryMerchantsSettle", sub_params);
                if (string.IsNullOrWhiteSpace(data))
                {
                    result.code = "-1";
                    result.message = "提交失败 对方服务器未响应";
                }
                else
                {
                    result = Newtonsoft.Json.JsonConvert.DeserializeObject<queryMerchantsSettle_result>(data);
                }
            }
            catch (Exception ex)
            {
                result.code = "-1";
                result.message = "提交发生异常=>" + ex.Message;
            }
            return result;
        }


 

        /// <summary>
        /// 3.7 服务商查询商户微信子商编接口
        /// </summary> 
        /// <returns></returns>
        public queryMerchantWXNo_result queryMerchantWXNo(queryMerchantWXNo Params)
        {
            queryMerchantWXNo_result result = new queryMerchantWXNo_result();
            SortedDictionary<string, object> entity_dic = new SortedDictionary<string, object>();
            foreach (var item in Params.GetType().GetProperties())
            {
                entity_dic.AddOrPeplace(item.Name, item.GetValue(Params));
            }
            string signData = Params.agentNo + Params.merchantNo + Params.productCode;
            string sign = JD_Tool.sign(signData);
            entity_dic.AddOrPeplace("sign", sign);
            string entity_content = JsonConvert.SerializeObject(entity_dic);
            string Content = JD_Tool.Des3EncryptECB(Convert.FromBase64String(Key), entity_content);
            SortedDictionary<string, string> sub_params = new SortedDictionary<string, string>();
            sub_params.AddOrPeplace("agentNo", AgentNo);
            sub_params.AddOrPeplace("entity", Content);
            try
            {
                string data = JD_Tool.post("https://psi.jd.com/merchant/status/queryMerchantWXNo", sub_params);
                if (string.IsNullOrWhiteSpace(data))
                {
                    result.code = "-1";
                    result.message = "提交失败 对方服务器未响应";
                }
                else
                { 
                    result = Newtonsoft.Json.JsonConvert.DeserializeObject<queryMerchantWXNo_result>(data);
                }
            }
            catch (Exception ex)
            {
                result.code = "-1";
                result.message = "提交发生异常=>" + ex.Message;
            }
            return result;
        }

        private static string[] NeedFile = new string[] {
            "blicUrla", "occUrla", "blicObaUrla", "blicTrcUrla", "lepUrla", "lepUrlb", "lepUrlc",
            "img", "enterimg", "innerimg", "cardPhoto",
            "settleManPhotoFront", "settleManPhotoBack", "settleProtocol", "settleHoldingIDCard", "settleHoldingBankCard"
        };


        private Queue<string> TryqueryJD = new Queue<string>();
        /// <summary>
        /// 入队处理
        /// </summary>
        /// <param name="Item"></param>
        public void ApplySingleQueueInQueue(string Kid)
        {
            try
            {
                TryqueryJD.Enqueue(Kid);
            }
            catch (Exception ex)
            {
                _log.Add_Log("处理入队程序异常=>" + ex.Message, "JD");
            }
        }
        /// <summary>
        /// 程序开始时候 开始监听程序
        /// </summary>
        public void ApplySingleQueueListen()
        {
            new Thread(() =>
            {
                try
                {
                    //获取所有未确认状态的数据
                    var NeedReInQueue = _jd_mongo.Linq_Search(s => s.Apply_IsAudit == false);
                    foreach (var item in NeedReInQueue)
                    {
                        ApplySingleQueueInQueue(item.KeyId);
                    }
                    while (true)
                    {
                        try
                        {
                            if (TryqueryJD.Any())
                            {
                                //取出队尾的一个数据
                                var kid = TryqueryJD.Dequeue();
                                var jdmodel = _jd_mongo.Linq_Search(s => s.KeyId == kid).FirstOrDefault();
                                if (jdmodel != null)
                                {
                                    if (jdmodel.Apply_IsAudit)
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        //只有获取了提交数据的才继续进行下去 否则不处理
                                        var queryResult = queryApplySingle(new queryApplySingle() { merchantNo = jdmodel.merchantNo, serialNo = DateTime.Now.ToString("yyyyMMddHHmmss") });
                                        if (queryResult.code == "0000")
                                        {
                                            bool IsAudit = true; //标记是否都审核通过了
                                            bool JDIsNoAudit = true;//标记激动支付是否申请通过了
                                            List<ApplySingleQueue> list = new List<ApplySingleQueue>();
                                            foreach (var item in queryResult.dataList)
                                            {
                                                //直接将结果记录下来 
                                                list.Add(new ApplySingleQueue()
                                                {
                                                    queryApplySingle = item
                                                });
                                                if (item.status == "0" || item.status == "1")
                                                {
                                                    //这种情况是审核状态不确认 需要继续轮询
                                                    IsAudit = false;
                                                }
                                                //修改对应提交值
                                                if (item.productNo == "401")
                                                {
                                                    _jd_mongo.update(s => s.KeyId == kid, (upset) =>
                                                    {
                                                        List<UpdateDefinition<JD_data_model>> uplist = new List<UpdateDefinition<JD_data_model>>()
                                                            {
                                                                upset.Set(s=>s.Subinfo.statewx,item.status), //更新结论
                                                                upset.Set(s=>s.Subinfo.statewxmsg,item.statusMsg) //标记状态
                                                            };
                                                        return uplist;
                                                    });
                                                }
                                                else if (item.productNo == "402")
                                                {
                                                    _jd_mongo.update(s => s.KeyId == kid, (upset) =>
                                                    {
                                                        List<UpdateDefinition<JD_data_model>> uplist = new List<UpdateDefinition<JD_data_model>>()
                                                            {
                                                                upset.Set(s=>s.Subinfo.statealipay,item.status), //更新结论
                                                                upset.Set(s=>s.Subinfo.statealipaymsg,item.statusMsg) //标记状态
                                                            };
                                                        return uplist;
                                                    });
                                                }
                                                else if (item.productNo == "403")
                                                {
                                                    if (item.status == "2")
                                                    {
                                                        JDIsNoAudit = false;
                                                    }
                                                    _jd_mongo.update(s => s.KeyId == kid, (upset) =>
                                                    {
                                                        List<UpdateDefinition<JD_data_model>> uplist = new List<UpdateDefinition<JD_data_model>>()
                                                            {
                                                                upset.Set(s=>s.Subinfo.statejd,item.status), //更新结论
                                                                upset.Set(s=>s.Subinfo.statejdmsg,item.statusMsg) //标记状态
                                                            };
                                                        return uplist;
                                                    });
                                                }
                                            }
                                            if (queryResult.dataList.Count != jdmodel.ApplyResultList.Count)
                                            {
                                                IsAudit = false;
                                            }
                                            if (!JDIsNoAudit)
                                            {
                                                //如果京东支付没通过 就算审核情况有问题 也不再继续请求结论了。因为有这一个结论足矣
                                                IsAudit = true;
                                            }
                                            //还有一种情况，如果403都没通过  那么其他两个可能连数据都没有  所以直接返回异常 
                                            if (!IsAudit)
                                            {
                                                //没有结论 重新入队
                                                ApplySingleQueueInQueue(kid);
                                            }
                                            //如果
                                            _jd_mongo.update(s => s.KeyId == kid, (upset) =>
                                            {
                                                List<UpdateDefinition<JD_data_model>> uplist = new List<UpdateDefinition<JD_data_model>>()
                                                    {
                                                    upset.Set(s=>s.Applyresult,list), //更新结论
                                                    upset.Set(s=>s.Apply_IsAudit,IsAudit) //标记状态
                                                    };
                                                return uplist;
                                            });
                                        }
                                        else
                                        {
                                            //请求失败= =  重新加入队列
                                            ApplySingleQueueInQueue(kid);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                Thread.Sleep(2000);
                            }
                        }
                        catch (Exception ex)
                        {
                            _log.Add_Log("处理出队程序异常=>" + ex.Message, "JD");
                            Thread.Sleep(2000);
                        }
                        finally
                        {
                            Thread.Sleep(1);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Thread.Sleep(1000);
                }
            }).Start();
        }
        #endregion
        #region  支付相关
        /// <summary>
        /// 6.4.7 获取京东的openid
        /// </summary>
        public getopenid_result get_openid(string piType, string merchantNo, string nowurl)
        {
            getopenid_result result = new getopenid_result();
            try
            {
                string openid = "";
                if (piType == "WX")
                {
                    openid = _context.HttpContext.Request.Cookies["JDwxopenid"] != null ? _context.HttpContext.Request.Cookies["JDwxopenid"].FirstOrDefault().ToString() : "";
                }
                else if (piType == "ALIPAY")
                {
                    openid = _context.HttpContext.Request.Cookies["JDalipayopenid"] != null ? _context.HttpContext.Request.Cookies["JDalipayopenid"].FirstOrDefault().ToString() : "";
                }
                else
                {
                    result.code = getopenid_result_code.参数不全;
                    return result;
                }
                if (string.IsNullOrWhiteSpace(openid))
                {
                    var model = _jd_mongo.Linq_Search(s => s.merchantNo == merchantNo).FirstOrDefault();
                    if (model == null)
                    {
                        result.code = getopenid_result_code.获取失败;
                        result.msg = "商户不存在";
                        return result;
                    }
                    if (string.IsNullOrWhiteSpace(model.desKey))
                    {
                        result.code = getopenid_result_code.获取失败;
                        result.msg = "商户密钥未获取";
                        return result;
                    }
                    //开始调用接口获取
                    GetOpenid_Params subparams = new GetOpenid_Params()
                    {
                        businessCode = "AGGRE",
                        version = AppSettingConfig["JD_Pay:version"].ToString(),
                        merchantNo = merchantNo,
                        piType = piType,
                        successPageUrl = $"{AppSettingConfig["JD_Pay:successPageUrl"].ToString() }?piType={piType}&returnUrl={nowurl}",
                        systemId = AppSettingConfig["JD_Pay:systemId"].ToString()
                    };
                    Jd_Post.Start_JD_Api(subparams, model, subparams.systemId, s =>
                    {
                        _log.Add_Log(Newtonsoft.Json.JsonConvert.SerializeObject(s), "JD_openid");
                        string url = $"{subparams.Request_URL}?merchantNo={s.merchantNo}&cipherJson={s.cipherJson}&sign={s.sign}&systemId={s.systemId}";
                        result.code = getopenid_result_code.需要跳转;
                        result.msg = "Success";
                        result.url = url;
                    });
                }
                else
                {
                    result.code = getopenid_result_code.获取成功;
                    result.msg = "Success";
                    result.openid = openid;
                }
                return result;
            }
            catch (Exception ex)
            {
                result.code = getopenid_result_code.获取失败;
                result.msg = ex.Message;
                return result;
            }
        }
        /// <summary>
        /// 6.4 统一下单接口
        /// </summary>
        /// <returns></returns>
        public unifiedOrder_Result unifiedOrder(Ex_params ex_params, orderInfo o_Item, List<goodsInfo> g_list, deviceInfo dev_Item, List<billSplitList> b_list)
        {
            unifiedOrder_Result result = new unifiedOrder_Result();
            if (string.IsNullOrWhiteSpace(ex_params.openid))
            {
                result.errCode = "-1";
                result.errCodeDes = "未能获取openid";
                return result;
            }
            if (string.IsNullOrWhiteSpace(ex_params.piType))
            {
                result.errCode = "-1";
                result.errCodeDes = "未知的支付方式";
                return result;
            }
            if (o_Item == null)
            {
                result.errCode = "-1";
                result.errCodeDes = "订单信息不能为空";
                return result;
            }
            if (g_list == null)
            {
                result.errCode = "-1";
                result.errCodeDes = "订单详情不能为空";
                return result;
            }
            var shopData = _jd_mongo.Linq_Search(s => s.userid == ex_params.baseuserid).FirstOrDefault();
            if (shopData == null)
            {
                result.errCode = "-1";
                result.errCodeDes = "未能获取商户资料";
                return result;
            }
            if (string.IsNullOrWhiteSpace(shopData.desKey))
            {
                result.errCode = "-1";
                result.errCodeDes = "商户未开通";
                return result;
            }
            //定义请求容器 准备发起一次下单
            unifiedOrder_Parms PostData = new unifiedOrder_Parms()
            {
                amount = o_Item.amount,
                billSplitList = (b_list == null ? null : Newtonsoft.Json.JsonConvert.SerializeObject(b_list)),
                deviceInfo = (dev_Item == null ? null : Newtonsoft.Json.JsonConvert.SerializeObject(dev_Item)),
                gatewayPayMethod = ex_params.PayMethod,
                goodsInfoList = Newtonsoft.Json.JsonConvert.SerializeObject(g_list),
                merchantNo = shopData.merchantNo,
                notifyUrl = notifyUrl,
                openId = ex_params.openid,
                orderInfo = Newtonsoft.Json.JsonConvert.SerializeObject(o_Item),
                outTradeIp = ex_params.IP,
                outTradeNo = o_Item.title,
                piType = ex_params.piType,
                productName = string.Join(",", g_list.Select(s => s.name).ToArray()),
                remark = ex_params.remark,
                returnParams = ex_params.returnParams,
                userId = ex_params.baseuserid,
            };
            _log.Add_Log("==支付请求==>" + Newtonsoft.Json.JsonConvert.SerializeObject(PostData), "JD_unifiedOrder");
            new Jd_Post().Start_JD_Api(PostData, shopData, systemId)
                .Start_Post<unifiedOrder_Result>((success, code, codedes, Postresult) =>
                {
                    _log.Add_Log("==支付结果==>" + Newtonsoft.Json.JsonConvert.SerializeObject(new
                    {
                        success,
                        code,
                        codedes,
                        Postresult
                    }), "JD_unifiedOrder");
                    if (!success)
                    {
                        result.errCode = code;
                        result.errCodeDes = codedes;
                    }
                    else
                    {
                        result = Postresult;
                    }
                });
            return result;
        }
        /// <summary>
        /// 6.5 订单查询
        /// </summary>
        /// <returns></returns>
        public querytrade_Result querytrade(string outTradeNo, string baseuserid)
        {
            querytrade_Result result = new querytrade_Result();
            if (string.IsNullOrWhiteSpace(outTradeNo))
            {
                result.errCode = "-1";
                result.errCodeDes = "请入参商户订单号";
                return result;
            }
            var shopData = _jd_mongo.Linq_Search(s => s.userid == baseuserid).FirstOrDefault();
            if (shopData == null)
            {
                result.errCode = "-1";
                result.errCodeDes = "未能获取商户资料";
                return result;
            }
            if (string.IsNullOrWhiteSpace(shopData.desKey))
            {
                result.errCode = "-1";
                result.errCodeDes = "商户未开通";
                return result;
            }
            //定义请求容器 准备发起一次下单
            querytrade_Params PostData = new querytrade_Params()
            {
                outTradeNo = outTradeNo,
                merchantNo = shopData.merchantNo
            };
            new Jd_Post().Start_JD_Api(PostData, shopData, systemId)
                .Start_Post<querytrade_Result>((success, code, codedes, Postresult) =>
                {
                    if (!success)
                    {
                        result.errCode = code;
                        result.errCodeDes = codedes;
                    }
                    else
                    {
                        result = Postresult;
                    }
                });
            return result;
        }
        /// <summary>
        /// 6.6 退款
        /// </summary>
        /// <returns></returns>
        public refund_Result refund(string refund_No, string baseuserid, long amount, orderInfo o_Item, List<goodsInfo> g_list, deviceInfo dev_Item = null, List<billSplitList> b_list = null)
        {
            refund_Result result = new refund_Result();
            if (string.IsNullOrWhiteSpace(o_Item.title))
            {
                result.errCode = "-1";
                result.errCodeDes = "请入参订单号";
                return result;
            }
            var shopData = _jd_mongo.Linq_Search(s => s.userid == baseuserid).FirstOrDefault();
            if (shopData == null)
            {
                result.errCode = "-1";
                result.errCodeDes = "未能获取商户资料";
                return result;
            }
            if (string.IsNullOrWhiteSpace(shopData.desKey))
            {
                result.errCode = "-1";
                result.errCodeDes = "商户未开通";
                return result;
            }
            //定义请求容器 准备发起一次退款
            refund_Params PostData = new refund_Params()
            {
                amount = amount,
                billSplitList = (b_list == null ? null : Newtonsoft.Json.JsonConvert.SerializeObject(b_list)),
                deviceInfo = (dev_Item == null ? null : Newtonsoft.Json.JsonConvert.SerializeObject(dev_Item)),
                orderInfo = Newtonsoft.Json.JsonConvert.SerializeObject(o_Item),
                goodsInfoList = Newtonsoft.Json.JsonConvert.SerializeObject(g_list),
                notifyUrl = refund_notifyUrl,
                merchantNo = shopData.merchantNo,
                outRefundNo = refund_No,
                outTradeNo = o_Item.title,
            };
            new Jd_Post().Start_JD_Api(PostData, shopData, systemId)
                .Start_Post<refund_Result>((success, code, codedes, Postresult) =>
                {
                    if (!success)
                    {
                        result.errCode = code;
                        result.errCodeDes = codedes;
                    }
                    else
                    {
                        result = Postresult;
                    }
                });
            return result;
        }
        /// <summary>
        ///   6.7 关闭订单 
        /// </summary>
        /// <returns></returns>
        public orderclose_Result orderclose(string outTradeNo, string baseuserid)
        {
            orderclose_Result result = new orderclose_Result();
            if (string.IsNullOrWhiteSpace(outTradeNo))
            {
                result.errCode = "-1";
                result.errCodeDes = "请入参订单号";
                return result;
            }
            var shopData = _jd_mongo.Linq_Search(s => s.userid == baseuserid).FirstOrDefault();
            if (shopData == null)
            {
                result.errCode = "-1";
                result.errCodeDes = "未能获取商户资料";
                return result;
            }
            if (string.IsNullOrWhiteSpace(shopData.desKey))
            {
                result.errCode = "-1";
                result.errCodeDes = "商户未开通";
                return result;
            }
            //定义请求容器 准备发起一次退款
            orderclose_Params PostData = new orderclose_Params()
            {
                merchantNo = shopData.merchantNo,
                outTradeNo = outTradeNo
            };
            new Jd_Post().Start_JD_Api(PostData, shopData, systemId)
                .Start_Post<orderclose_Result>((success, code, codedes, Postresult) =>
                {
                    if (!success)
                    {
                        result.errCode = code;
                        result.errCodeDes = codedes;
                    }
                    else
                    {
                        result = Postresult;
                    }
                });
            return result;
        }
        /// <summary>
        ///   6.9 查询退款 
        /// </summary>
        /// <returns></returns>
        public queryrefund_Result queryrefund(string outRefundNo, string baseuserid)
        {
            queryrefund_Result result = new queryrefund_Result();
            if (string.IsNullOrWhiteSpace(outRefundNo))
            {
                result.errCode = "-1";
                result.errCodeDes = "请入参退款订单";
                return result;
            }
            var shopData = _jd_mongo.Linq_Search(s => s.userid == baseuserid).FirstOrDefault();
            if (shopData == null)
            {
                result.errCode = "-1";
                result.errCodeDes = "未能获取商户资料";
                return result;
            }
            if (string.IsNullOrWhiteSpace(shopData.desKey))
            {
                result.errCode = "-1";
                result.errCodeDes = "商户未开通";
                return result;
            }
            //定义请求容器 准备发起一次退款
            queryrefund_Params PostData = new queryrefund_Params()
            {
                merchantNo = shopData.merchantNo,
                outRefundNo = outRefundNo
            };
            new Jd_Post().Start_JD_Api(PostData, shopData, systemId)
                .Start_Post<queryrefund_Result>((success, code, codedes, Postresult) =>
                {
                    if (!success)
                    {
                        result.errCode = code;
                        result.errCodeDes = codedes;
                    }
                    else
                    {
                        result = Postresult;
                    }
                });
            return result;
        }
        /// <summary>
        ///   6.11 下载对账单 
        /// </summary>
        /// <returns></returns>
        public bill_Result bill(string billDate, string baseuserid, string billType = null)
        {
            bill_Result result = new bill_Result();
            if (string.IsNullOrWhiteSpace(billDate))
            {
                result.errCode = "-1";
                result.errCodeDes = "请输入对账日期(yyyyMMdd)";
                return result;
            }
            var shopData = _jd_mongo.Linq_Search(s => s.userid == baseuserid).FirstOrDefault();
            if (shopData == null)
            {
                result.errCode = "-1";
                result.errCodeDes = "未能获取商户资料";
                return result;
            }
            if (string.IsNullOrWhiteSpace(shopData.desKey))
            {
                result.errCode = "-1";
                result.errCodeDes = "商户未开通";
                return result;
            }
            //定义请求容器 准备发起一次退款
            bill_Params PostData = new bill_Params()
            {
                merchantNo = shopData.merchantNo,
                billDate = billDate,
                billType = billType
            };
            new Jd_Post().Start_JD_Api(PostData, shopData, systemId)
                .Start_Post<bill_Result>((success, code, codedes, Postresult) =>
                {
                    if (!success)
                    {
                        result.errCode = code;
                        result.errCodeDes = codedes;
                    }
                    else
                    {
                        result = Postresult;
                    }
                });
            return result;
        }
        /// <summary>
        ///    6.12   支付结果通知
        /// </summary>
        public paynotify_Result payNotify(Stream InputStream)
        {
            paynotify_Result result = new paynotify_Result();
            string info = "";
            Jd_Post.Start_Notify<paynotify_Result>(InputStream,
            (merchantNo) =>
            {
                var shopData = _jd_mongo.Linq_Search(s => s.merchantNo == merchantNo).FirstOrDefault();
                return shopData;
            },
            (a, notify, data) =>
            {
                if (!a.success)
                {
                    result.errCode = a.errCode;
                    result.errCodeDes = a.errCodeDes;
                }
                else
                {
                    result = notify;
                }
            }, ref info);
            return result;
        }
        /// <summary>
        ///  6.13   退款结果通知
        /// </summary>
        public refundnotify_Result refundNotify(Stream InputStream)
        {
            refundnotify_Result result = new refundnotify_Result();
            string info = "";
            Jd_Post.Start_Notify<refundnotify_Result>(InputStream,
            (merchantNo) =>
            {
                var shopData = _jd_mongo.Linq_Search(s => s.merchantNo == merchantNo).FirstOrDefault();
                return shopData;
            },
            (a, notify,data) =>
            { 
                if (!a.success)
                {
                    result.errCode = a.errCode;
                    result.errCodeDes = a.errCodeDes;
                }
                else
                {
                    result = notify;
                }
            },ref info);
            _log.Add_Log(info, "JD_payNotify");
            return result;
        }



        /// <summary>
        /// 6.5 订单查询
        /// </summary>
        /// <returns></returns>
        public querytrade_Result querytrade_for_rk(string outTradeNo, string merchantNo, string desKey, string mdKey)
        {
            querytrade_Result result = new querytrade_Result();
            if (string.IsNullOrWhiteSpace(outTradeNo))
            {
                result.errCode = "-1";
                result.errCodeDes = "请入参商户订单号";
                return result;
            }

            //var shopData = _jd_mongo.Linq_Search(s => s.userid == baseuserid).FirstOrDefault();
            //if (shopData == null)
            //{
            //    result.errCode = "-1";
            //    result.errCodeDes = "未能获取商户资料";
            //    return result;
            //}
            //if (string.IsNullOrWhiteSpace(shopData.desKey))
            //{
            //    result.errCode = "-1";
            //    result.errCodeDes = "商户未开通";
            //    return result;
            //}
            //定义请求容器 准备发起一次下单
            querytrade_Params PostData = new querytrade_Params()
            {
                outTradeNo = outTradeNo,
                merchantNo = merchantNo
            };
            new Jd_Post().Start_JD_Api(PostData, new JD_data_model()
            {
                merchantNo = merchantNo,
                desKey = desKey,
                mdKey = mdKey
            }, systemId)
                .Start_Post<querytrade_Result>((success, code, codedes, Postresult) =>
                {
                    if (!success)
                    {
                        result.errCode = code;
                        result.errCodeDes = codedes;
                    }
                    else
                    {
                        result = Postresult;
                    }
                });
            return result;
        }

        /// <summary>
        ///   6.9 查询退款 
        /// </summary>
        /// <returns></returns>
        public queryrefund_Result queryrefund_for_rk(string outRefundNo, string merchantNo, string desKey, string mdKey)
        {
            queryrefund_Result result = new queryrefund_Result();
            if (string.IsNullOrWhiteSpace(outRefundNo))
            {
                result.errCode = "-1";
                result.errCodeDes = "请入参退款订单";
                return result;
            }
            //var shopData = _jd_mongo.Linq_Search(s => s.userid == baseuserid).FirstOrDefault();
            //if (shopData == null)
            //{
            //    result.errCode = "-1";
            //    result.errCodeDes = "未能获取商户资料";
            //    return result;
            //}
            //if (string.IsNullOrWhiteSpace(shopData.desKey))
            //{
            //    result.errCode = "-1";
            //    result.errCodeDes = "商户未开通";
            //    return result;
            //}
            //定义请求容器 准备发起一次退款
            queryrefund_Params PostData = new queryrefund_Params()
            {
                merchantNo = merchantNo,
                outRefundNo = outRefundNo
            };
            new Jd_Post().Start_JD_Api(PostData, new JD_data_model()
            {
                merchantNo = merchantNo,
                desKey = desKey,
                mdKey = mdKey
            }, systemId)
                .Start_Post<queryrefund_Result>((success, code, codedes, Postresult) =>
                {
                    if (!success)
                    {
                        result.errCode = code;
                        result.errCodeDes = codedes;
                    }
                    else
                    {
                        result = Postresult;
                    }
                });
            return result;
        }
        #endregion
    }
}
